<template>
  <div class="forgot-container">
    <div class="forgot-box">
      <div class="forgot-header">
        <img src="@/assets/airline-logo.png" alt="航空公司Logo" class="logo">
        <h1>天津滨海机场航班分析及管理平台</h1>
        <p class="subtitle">重置密码</p>
      </div>

      <el-form
        ref="forgotFormRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="forgot-form"
        @submit.prevent="handleSubmit"
        v-if="!showResetForm"
      >
        <el-form-item label="注册邮箱" prop="email">
          <el-input
            v-model="form.email"
            placeholder="请输入注册邮箱"
            size="large"
          >
            <template #prefix>
              <el-icon class="input-icon"><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            size="large"
            :loading="loading"
            class="forgot-btn"
          >
            获取验证码
          </el-button>
        </el-form-item>
      </el-form>

      <el-form
        ref="resetFormRef"
        :model="resetForm"
        :rules="resetRules"
        label-position="top"
        class="forgot-form"
        @submit.prevent="handleReset"
        v-else
      >
        <el-form-item label="验证码" prop="code">
          <div class="code-input-container">
            <el-input
              v-model="resetForm.code"
              placeholder="请输入收到的验证码"
              size="large"
            >
              <template #prefix>
                <el-icon class="input-icon"><Key /></el-icon>
              </template>
            </el-input>
            <el-button
              v-if="countdown > 0"
              size="large"
              disabled
              class="countdown-btn"
            >
              重新发送({{ countdown }}s)
            </el-button>
            <el-button
              v-else
              size="large"
              @click="handleResendCode"
              class="resend-btn"
            >
              重新发送
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            size="large"
            show-password
          >
            <template #prefix>
              <el-icon class="input-icon"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            size="large"
            show-password
          >
            <template #prefix>
              <el-icon class="input-icon"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            size="large"
            :loading="loading"
            class="forgot-btn"
          >
            重置密码
          </el-button>
        </el-form-item>
      </el-form>

      <div class="forgot-footer">
        <el-link type="info" @click="$router.push('/login')">
          <el-icon><ArrowLeft /></el-icon> 返回登录
        </el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { sendVerificationCode, resetPassword } from '@/api/auth'
import { Message, ArrowLeft, Key, Lock } from '@element-plus/icons-vue'

const router = useRouter()
const form = ref({
  email: ''
})

const resetForm = ref({
  email: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const countdown = ref(0)
const countdownInterval = ref(null)

const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ]
}
const resetRules = {
  code: [
    { required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
    { min: 6, max: 6, message: '验证码为6位数字', trigger: ['blur', 'change'] }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: ['blur', 'change'] },
    { min: 6, message: '密码长度不能少于6位', trigger: ['blur', 'change'] }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: ['blur', 'change'] },
    { validator: validatePass2, trigger: ['blur', 'change'] }
  ]
}

function validatePass2 (rule, value, callback) {
  if (value !== resetForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const forgotFormRef = ref(null)
const resetFormRef = ref(null)
const loading = ref(false)
const showResetForm = ref(false)

const startCountdown = () => {
  countdown.value = 60
  countdownInterval.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownInterval.value)
    }
  }, 1000)
}

const handleSubmit = async () => {
  try {
    await forgotFormRef.value.validate()
    loading.value = true
    console.log('准备发送验证码到邮箱:', form.value.email)

    const response = await sendVerificationCode(form.value.email)
    console.log('后端响应:', response)

    if (response.data && response.data.message) {
      ElMessage.success(response.data.message)
    } else {
      ElMessage.success('验证码已发送')
    }
    resetForm.value.email = form.value.email
    showResetForm.value = true
    startCountdown()
  } catch (error) {
    console.error('完整错误信息:', error)
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
      const msg = error.response.data.message || '验证码发送失败'
      ElMessage.error(msg)
    } else if (error.request) {
      console.error('请求对象:', error.request)
      ElMessage.error('网络错误，请检查连接')
    } else {
      ElMessage.error('请求配置错误: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

const handleResendCode = async () => {
  try {
    await sendVerificationCode(resetForm.value.email)
    ElMessage.success('验证码已重新发送')
    startCountdown()
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '发送失败')
    }
  }
}

const handleReset = async () => {
  try {
    await resetFormRef.value.validate()
    loading.value = true
    await resetPassword({
      email: resetForm.value.email,
      verificationCode: resetForm.value.code,
      newPassword: resetForm.value.newPassword
    })
    ElMessage.success('密码重置成功，请重新登录')
    router.push('/login')
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '重置失败')
    }
  } finally {
    loading.value = false
  }
}

onBeforeUnmount(() => {
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value)
  }
})
</script>

<style scoped>
.forgot-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('@/assets/airport-bg.jpg') no-repeat center center;
  background-size: cover;
  position: relative;
  padding: 20px;
}

.forgot-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 0;
}

.forgot-box {
  width: 420px;
  padding: 35px;
  background: rgba(255, 255, 255, 0.96);
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  position: relative;
  z-index: 1;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.logo {
  height: 55px;
  margin-bottom: 18px;
  transition: transform 0.3s;
}

.logo:hover {
  transform: scale(1.05);
}

.forgot-header {
  text-align: center;
  margin-bottom: 25px;
}

.forgot-header h1 {
  font-size: 22px;
  margin-bottom: 8px;
  color: #333;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.subtitle {
  font-size: 16px;
  color: #666;
  letter-spacing: 0.3px;
}

.forgot-form {
  margin-top: 18px;
}

.code-input-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.countdown-btn,
.resend-btn {
  width: 120px;
}

.forgot-btn {
  width: 100%;
  margin-top: 12px;
  font-size: 16px;
  letter-spacing: 2px;
  height: 44px;
  transition: all 0.3s;
}

.forgot-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.forgot-footer {
  margin-top: 18px;
  text-align: center;
}

.forgot-footer .el-link {
  transition: color 0.3s;
}

.forgot-footer .el-link:hover {
  color: #409EFF !important;
}

.input-icon {
  color: #999;
  margin-right: 8px;
  font-size: 18px;
}

@media (max-width: 480px) {
  .forgot-box {
    width: 90%;
    padding: 25px;
  }

  .forgot-header h1 {
    font-size: 20px;
  }
}
</style>
